package com.wjc.file.controller.admin.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetMezzanineInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.wjc.server.dto.CommonDto;
import com.wjc.server.dto.FileDto;
import com.wjc.server.enums.FileUseEnum;
import com.wjc.server.service.FileService;
import com.wjc.server.util.Base64ToMultipartFile;
import com.wjc.server.util.SnowFlake;
import com.wjc.server.util.VodUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController("webVodController")
@RequestMapping("/web")
public class VodController {

    private static final Logger LOG= LoggerFactory.getLogger(VodController.class);
    public static final String BUSINESS_NAME = "OSS上传";

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private FileService fileService;

    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Value("${file.path}")
    private String FILE_PATH;

    @Value("${vod.accessKeyId}")
    private String accessKeyId;

    @Value("${vod.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.ossDomain}")
    private String ossDomain;

    @Value("${oss.bucket}")
    private String bucket;


    @PostMapping("/vod")
    public CommonDto upload(@RequestBody FileDto fileDto) {
        String use=fileDto.getUse();
        String key =fileDto.getKey();
        String suffix=fileDto.getSuffix();
        String shardBase64=fileDto.getShard();
        MultipartFile shard = Base64ToMultipartFile.base64ToMultipart(shardBase64);

        //保存文件到本地
        FileUseEnum fileUseEnum= FileUseEnum.getByCode(use);
        //获取文件后缀,小写
//        Long key = snowFlake.nextId();
        //如果文件夹不存在则创建
        String dir=fileUseEnum.name().toLowerCase();
        //File.separator,根据操作系统不同生成不同的/或\
       //String path=dir+File.separator+key +"." +suffix;


        //生成文件路径,例如: course/wad2123dfa.mp4,不含".1"
        String filepath= new StringBuffer(dir)
                .append("/")
                .append(key)
                .append(".")
                .append(suffix).toString();

        String vod="";
        String fileUrl="";
        try {
            // 初始化VOD客户端并获取上传地址和凭证
            DefaultAcsClient vodClient = VodUtil.initVodClient(accessKeyId, accessKeySecret);
            CreateUploadVideoResponse createUploadVideoResponse = VodUtil.createUploadVideo(vodClient, filepath);
            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            vod = createUploadVideoResponse.getVideoId();
            JSONObject uploadAuth = JSONObject.parseObject(
                    Base64.decodeBase64(createUploadVideoResponse.getUploadAuth()), JSONObject.class);
            JSONObject uploadAddress = JSONObject.parseObject(
                    Base64.decodeBase64(createUploadVideoResponse.getUploadAddress()), JSONObject.class);
            // 使用UploadAuth和UploadAddress初始化OSS客户端
            OSSClient ossClient = VodUtil.initOssClient(uploadAuth, uploadAddress);
            // 上传文件，注意是同步上传会阻塞等待，耗时与文件大小和网络上行带宽有关
            VodUtil.uploadLocalFile(ossClient, uploadAddress, shard.getInputStream());
            LOG.info("上传视频成功, vod : " + vod);
            GetMezzanineInfoResponse response = VodUtil.getMezzanineInfo(vodClient, vod);
            System.out.println("获取视频信息, response : " + JSON.toJSONString(response));
            fileUrl = response.getMezzanine().getFileURL();

            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            LOG.info("上传视频失败, ErrorMessage : " + e.getLocalizedMessage(), e);
        }

        //保存文件记录
        LOG.info("保存文件记录开始");
        fileDto.setPath(filepath);
        fileDto.setVod(vod);
        fileService.save(fileDto);
        CommonDto commonDto = new CommonDto<>();
        fileDto.setPath(fileUrl);
        commonDto.setContent(fileDto);
        return commonDto;
    }

    @GetMapping("/get-auth/{vod}")
    public CommonDto getAuth(@PathVariable String vod) throws ClientException, com.aliyuncs.exceptions.ClientException {
        LOG.info("获取播放授权开始: ");
        CommonDto responseDto = new CommonDto();
        DefaultAcsClient client = VodUtil.initVodClient(accessKeyId, accessKeySecret);
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        try {
            response = VodUtil.getVideoPlayAuth(client, vod);
            LOG.info("授权码 = {}", response.getPlayAuth());
            responseDto.setContent(response.getPlayAuth());
            //VideoMeta信息
            LOG.info("VideoMeta = {}", JSON.toJSONString(response.getVideoMeta()));
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
        }
        LOG.info("获取播放授权结束");
        return responseDto;
    }



}
